﻿using System;
using System.Management;
using ArtOfTest.WebAii.Win32.Dialogs;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ArtOfTest.WebAii.TestTemplates;
using ArtOfTest.WebAii.TestAttributes;
using ArtOfTest.WebAii.Controls.HtmlControls;
using AutomationResearch.Settings;

namespace AutomationResearch
{
    /// <summary>
    /// Research : AutoBot
    /// this little program is going to spider a site
    /// and test to make sure the pages do not crash
    /// 
    /// Ideas : 
    /// 
    /// 1) We'll need to randomize the collection of links per page and navigate
    /// 2) We'll need to avoid the dead ends by avoiding certain urls
    /// 3) Optional : perhaps we want to execute some set of commands when we reach certain page?
    /// 4) Ability to set number of hours you want to execute
    /// </summary>
    [TestClass]
    public class AutoBot : BaseTest
    {
        public AutoBot()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        #region Members

        private DateTime _startTime;
        private int _testDuration = 1;  //in minutes


        #region Properties
        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get;
            set;
        }

        #endregion

        #endregion

        #region Initialization and Cleanup

        [ClassInitialize()]
        public static void MyClassInitialize(TestContext testContext)
        {
            
        }

        [ClassCleanup()]
        public static void MyClassCleanup()
        {
            
        }


        [TestInitialize()]
        public void MyTestInitialize()
        {
            Initialize(this.TestContext.TestLogsDir, new TestContextWriteLine(this.TestContext.WriteLine));
            SetTestMethod(this, (string)TestContext.Properties["TestName"]);
        }


        [TestCleanup()]
        public void MyTestCleanup()
        {
            this.CleanUp();
        }

        #endregion

        #region Tests


        /// <summary>
        /// the original version of autobot
        /// very simple site crawler
        /// empty guidence and empty of commands
        /// </summary>
        [TestMethod]
        [Dialog(DialogButton.OK)]
        [Timeout(43200000)]
        public void AutoBot100()
        {
            Manager.Settings.AnnotateExecution = true;
            Manager.Settings.LogAnnotations = true;
            Manager.LaunchNewBrowser();
            //ActiveBrowser.Annotator.Settings.BackColor = System.Drawing.Color.SkyBlue;
            //ActiveBrowser.Annotator.Settings.Color = System.Drawing.Color.Black;
            //ActiveBrowser.Annotator.Annotate("This is automation bot", 2000, OffsetReference.TopCenter);
            ActiveBrowser.NavigateTo("http://www.vptest.com");
            try
            {
                ActiveBrowser.Actions.InvokeScript("javascript:Editor.deleteAllText();");
            }
            catch (Exception)
            {
                
                throw;
            }
            /* Read the initial time. */
            _startTime = DateTime.Now;
            Crawl();
        }

        [TestMethod]
        [Dialog(DialogButton.OK)]
        public void EmptyTextFields()
        {
            Manager.LaunchNewBrowser();
            ActiveBrowser.NavigateTo(
                "http://www.vptest.com/vp/ns/studio3.aspx?pf_id=088&combo=70527.79.22.103341|103341|137|0&uei=121094&icparts=yes&ag=true&combo_id=117740&ssc=1&filter=9%3a10013||1%2c4%3a10003||1%2c3%3a10001||1&xnav=previews&xnid=button&rd=3&referer=http%3a%2f%2fwww.vptest.com%2fgallery.aspx%3fpg%3d1%26xnav%3dHowToDesign");

        }

        #endregion

        #region Private Functions

        private void Crawl()
        {
            var winQuery = new ObjectQuery("SELECT * FROM Win32_LogicalMemoryConfiguration");
            var searcher = new ManagementObjectSearcher(winQuery);

            string url;
            do
            {
                ActiveBrowser.WaitUntilReady();
                ActiveBrowser.RefreshDomTree();
                FindLinks();
                ActiveBrowser.Annotator.Annotate("Page : " + ActiveBrowser.Url);
                //foreach (ManagementObject item in searcher.Get())
                //{
                //    ActiveBrowser.Annotator.Annotate("*** Total Space = " + item["TotalPageFileSpace"]);
                //    ActiveBrowser.Annotator.Annotate("*** Total Physical Memory = " + item["TotalPhysicalMemory"]);
                //    ActiveBrowser.Annotator.Annotate("*** Total Virtual Memory = " + item["TotalVirtualMemory"]);
                //    ActiveBrowser.Annotator.Annotate("*** Available Virtual Memory = " + item["AvailableVirtualMemory"]);
                //}
            } while (!IsTimeExpired());

        }

        private void FindLinks()
        {
            var links = Find.AllByTagName("a");
            if (links.Count > 0)
            {
                var randnum = new Random();
                int i = randnum.Next(links.Count - 1);
                //Console.WriteLine("> Clicking On {0}[{1}]", links[i].GetAttribute("Href"), i);
                Actions.Click(links[i]);
                //links[i].Click();
            }
            else
            {
                Assert.Inconclusive("Cannot move any further");
            }
        }

        private bool IsTimeExpired()
        {
            DateTime now = DateTime.Now;

            /* Compute the duration between the initial and the end time. */
            TimeSpan duration = now - _startTime;
            if (duration.Minutes >= _testDuration)
            {
                return true;
            }
            else
                return false;
        }

        #endregion


    }
}
